
#import "UIViewController+WXSNavigationBarItem.h"

@implementation UIViewController (WXSNavigationBarItem)

- (void)setupLeftBarButtonWithTitle:(NSString *)title action:(SEL)action
{
    self.navigationItem.leftBarButtonItem = [self barButtonItemWithTitle:title action:action];
}

- (void)setupLeftBarButtonWithImageName:(NSString *)imageName action:(SEL)action
{
    self.navigationItem.leftBarButtonItem = [self barButtonItemWithImageName:imageName action:action];
}

- (void)setupRightBarButtonWithTitle:(NSString *)title action:(SEL)action
{
    self.navigationItem.rightBarButtonItem = [self barButtonItemWithTitle:title action:action];
}

-(void)setupRightBarButtonWithImageName:(NSString *)imageName action:(SEL)action
{
    self.navigationItem.rightBarButtonItem = [self barButtonItemWithImageName:imageName action:action];
}

- (void)setupBackBarButton
{
    [self setupLeftBarButtonWithImageName:@"back" action:@selector(backButtonTaped:)];
}

#pragma mark - private method

- (UIBarButtonItem *)barButtonItemWithTitle:(NSString *)title action:(SEL)action
{
    CGRect rect = [title boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSForegroundColorAttributeName:[UIColor whiteColor], NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
    UIView *view = [[UIView alloc]initWithFrame:rect];
    UIButton *button = [[UIButton alloc]initWithFrame:rect];
    [button setTitle:title forState:UIControlStateNormal];
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    button.titleLabel.font = [UIFont systemFontOfSize:14];
    [view addSubview:button];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithCustomView:view];
    return barButton;
}

- (UIBarButtonItem *)barButtonItemWithImageName:(NSString *)imageName action:(SEL)action
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 24, 24)];
    UIButton *button = [[UIButton alloc]initWithFrame:view.bounds];
    [button setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc]initWithCustomView:view];
    return barButton;
}

- (void)backButtonTaped:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
